#####################################################################
#                                                                   #
#  THIS IS A SOURCE CODE FILE FROM A PROGRAM TO INTERACT WITH THE   #
# LBRY PROTOCOL ( lbry.com ). IT WILL USE THE LBRY SDK ( lbrynet )  #
# FROM THEIR REPOSITORY ( https://github.com/lbryio/lbry-sdk )      #
# WHICH I GONNA PRESENT TO YOU AS A BINARY. SINCE I DID NOT DEVELOP #
# IT AND I'M LAZY TO INTEGRATE IN A MORE SMART WAY. THE SOURCE CODE #
# OF THE SDK IS AVAILABLE IN THE REPOSITORY MENTIONED ABOVE.        #
#                                                                   #
#      ALL THE CODE IN THIS REPOSITORY INCLUDING THIS FILE IS       #
# (C) J.Y.Amihud and Other Contributors 2021. EXCEPT THE LBRY SDK.  #
# YOU CAN USE THIS FILE AND ANY OTHER FILE IN THIS REPOSITORY UNDER #
# THE TERMS OF GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER    #
# VERSION. TO FIND THE FULL TEXT OF THE LICENSE GO TO THE GNU.ORG   #
# WEBSITE AT ( https://www.gnu.org/licenses/gpl-3.0.html ).         #
#                                                                   #
# THE LBRY SDK IS UNFORTUNATELY UNDER THE MIT LICENSE. IF YOU ARE   #
# NOT INTENDING TO USE MY CODE AND JUST THE SDK. YOU CAN FIND IT ON #
# THEIR OFFICIAL REPOSITORY ABOVE. THEIR LICENSE CHOICE DOES NOT    #
# SPREAD ONTO THIS PROJECT. DON'T GET A FALSE ASSUMPTION THAT SINCE #
# THEY USE A PUSH-OVER LICENSE, I GONNA DO THE SAME. I'M NOT.       #
#                                                                   #
# THE LICENSE CHOSEN FOR THIS PROJECT WILL PROTECT THE 4 ESSENTIAL  #
# FREEDOMS OF THE USER FURTHER, BY NOT ALLOWING ANY WHO TO CHANGE   #
# THE LICENSE AT WILL. SO NO PROPRIETARY SOFTWARE DEVELOPER COULD   #
# TAKE THIS CODE AND MAKE THEIR USER-SUBJUGATING SOFTWARE FROM IT.  #
#                                                                   #
#####################################################################

# This file will perform a simple search on the LBRY network.

from subprocess import *
import json

from flbry import url
from flbry.variables import *

def history():

    # This function will output wallet history.

    # So instead we are going to request only the first 20 and let
    # the user load more.

    page_size = 20
    page = 1
    
    while True:

        # Printing the search query and page number
        print("    "+clr["bold"]+clr["bdma"], " WALLET HISTORY",
              wdth(" ", 19), "         PAGE :",
              wdth(page, 3),
              wdth(" ", 32)+clr["norm"])

       
        out = check_output(["flbry/lbrynet",
                         "transaction", "list",
                         '--page='+str(page),
                         '--page_size='+str(page_size)])

        # Now we want to parse the json

        try:
            out = json.loads(out)
        except:
            print("   Connect to LBRY first.")
            return

        # Print the categories
        print("    "+clr["bold"]+clr["bdma"],wdth(" ", 3),
                      "", wdth("CONFIRMED", 10),
                      "",  wdth("AMOUNT", 10),
                      "",  wdth("TIP", 9),
                      "", wdth("PUBLICATION", 17)+wdth(" ", 31)+clr["norm"])
        
        
        try:
            

            # List what we found
            for n, i in enumerate(out["items"]):

                # This will make each new line a different shade
                if n % 2:
                    b = "d"
                else:
                    b = "b"
                
                value = i["value"]
                if int(i["confirmations"]) < 10:
                    concol = "tbrd"
                elif int(i["confirmations"]) < 100:
                    concol = "tbyl"
                elif int(i["confirmations"]) < 500:
                    concol = "tbgr"
                else:
                    concol = "tbwh"
                conf = clr["norm"]+clr["bold"]+clr["tbwh"]+clr["b"+b+"bu"]+clr[concol]+\
                    " "+wdth(i["confirmations"], 10)+" "

                s = "    "+clr["bold"]+clr["b"+b+"ma"]+" "+\
                    wdth(n, 3)+" "+\
                    conf+" "+\
                    clr["norm"]+clr["bold"]+clr["b"+b+"bu"]+\
                    wdth(value, 12)+" LBC " 
                    
                try:
                    if i["support_info"][0]["is_tip"]:
                        if i["support_info"][0]["is_spent"]:
                            s = s + " [v] "
                        else:
                            s = s + " [ ] "
                    s = s + wdth(i["support_info"][0]["claim_name"], 48)
                except:
                    s = s + wdth(" ", 53)

           
                print(s+" "+clr["norm"])
                

            
            # Tell the user that he might want to load more
            print("    "+clr["bold"]+clr["bdma"],
                  "                   ---type more to load more---",
                   wdth(" ",40)+clr["norm"])
            page = page +1

        # Error messages    
        except Exception as e:
            if "code" in out:
                print("    Error code: ", out["code"]  )
                if out["code"] == -32500:
                    print("   SDK is still starting. Patience!")
            else:
                raise()
                print("    Error :", e)
            return

        # Making sure that we stop every time a new page is reached
        c = input(" :: ")
        if c != "more":
            break
    try:
        c = int(c)
        
    except:
        return

    while True:
        try:
            url.get(out["items"][c]["support_info"][0]["claim_name"]+"#"+out["items"][c]["support_info"][0]["claim_id"])
        except:
            pass
        c = input(" :: ")
        if not c:
            break
        try:
            c = int(c)
        except:
            return
